//
//  ChartViewCell.swift
//  HealthMonitoring
//
//  Created by YTYanK on 04/12/2018.
//  Copyright © 2018 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON
import Charts

class ChartViewCell: HMTableViewCell {
    
    
    lazy var lineChartView: LineChartView = {
        let _lineChartView = LineChartView.init(frame: CGRect.init(x: 0, y: 0, width: configure.shareConfigure.screenWidth, height: 350));
        _lineChartView.delegate = self;
        _lineChartView.backgroundColor = UIColor.white;  //UIColor.init(r: 0/255, g: 0/255, b: 30/255);
        _lineChartView.doubleTapToZoomEnabled = false;  //指示是否启用双抽头缩放的标志
        _lineChartView.scaleXEnabled = true; //是否启用缩放功能？（通过手势放大和缩小）图表（这不影响拖动）。
        // -- 新加
        _lineChartView.chartDescription?.enabled = false
        _lineChartView.dragEnabled = true;
        _lineChartView.setScaleEnabled(true);
        _lineChartView.pinchZoomEnabled = true;
        
        //---
        _lineChartView.scaleYEnabled = true;
        _lineChartView.chartDescription?.text = "";
        
        _lineChartView.noDataText = "暂时没有数据";
        _lineChartView.noDataTextColor = UIColor.gray;
        _lineChartView.noDataFont = UIFont.boldSystemFont(ofSize: 14);
        
        
        // y
        _lineChartView.rightAxis.enabled = false;
        let leftAxis = _lineChartView.leftAxis;
        leftAxis.labelCount = 10;
        leftAxis.forceLabelsEnabled = false;
        leftAxis.labelTextColor = UIColor.black;
        leftAxis.axisLineColor = UIColor.red;
        leftAxis.labelFont = UIFont.systemFont(ofSize: 12);
        leftAxis.labelPosition = .outsideChart;
        leftAxis.gridColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1.0); //网格颜色
        leftAxis.gridLineDashLengths = [2, 1.5];  //设置点线
        leftAxis.gridAntialiasEnabled = false;
        leftAxis.axisMaximum = 500;  //最大刻度值
        leftAxis.axisMinimum = 0;  //最小刻度值
        leftAxis.granularity = 50 //最小间隔
//        leftAxis.drawZeroLineEnabled = true
        // x
        let xAxis = _lineChartView.xAxis;
        xAxis.granularityEnabled = true;
        xAxis.labelTextColor = UIColor.black;
        xAxis.labelFont = UIFont.systemFont(ofSize: 12.0);
        xAxis.labelPosition = .bottom;
        xAxis.gridColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1.0);
        xAxis.gridAntialiasEnabled  =  false // 网格？
        xAxis.axisLineColor = UIColor.black;
        xAxis.labelCount = 24;
        xAxis.labelRotationAngle = 25 //刻度文字倾斜角度
        
        //指定刻度之间的最小间距
//        xAxis.axisMinimum = -15;
//        xAxis.axisMaximum = 24;
//        xAxis.granularity = 1; //间隔
        
        return _lineChartView;
        
    }()
    
    var xValues = Array<String>()
    var yValues = Array<String>()
    var chartValues = Array<String>()
    
      //填充数据 - 初始化
    func drawLineChart(){
        for i in 0..<24 {
            xValues.append("\(i + 1)")
        }
        

        
        lineChartView.xAxis.valueFormatter = VDChartAxisValueFormatter.init(xValues as NSArray);
//        let formatter = NumberFormatter()
//        formatter.positiveSuffix = "%"
//        lineChartView.leftAxis.valueFormatter =  DefaultAxisValueFormatter(formatter: formatter)
          lineChartView.leftAxis.valueFormatter = VDChartAxisValueFormatter.init()
        // 带图片的数据- 点的图  ChartDataEntry(x: Double(i), y: val, icon: #imageLiteral(resourceName: "icon"))

         // y1
        var yDataArray1 = [ChartDataEntry]();  //数组数据
       
        //这里放数据？
        for i in 0...1 {
            var dou: Double  =  Double(i) * Double(23)
            let entry = ChartDataEntry.init(x: dou, y: Double(-2));
            yDataArray1.append(entry);
        }
        let set1 = LineChartDataSet.init(values: yDataArray1, label: "蓝色");
        set1.colors = [configure.shareConfigure.HMColor1];
        set1.circleRadius = 5;  //点的大小
        set1.drawCircleHoleEnabled = true;  //圆孔启用- 在点上加多一个点
        set1.circleHoleRadius = 3; //圆孔启用- 在点上加多一个点的大小
        set1.drawCirclesEnabled = true;//绘制转折点
        set1.setCircleColor(.gray) //点的颜色
        set1.lineWidth = 2.0;
        set1.drawValuesEnabled = false; //不显示点上的值
        set1.valueFont = UIFont.systemFont(ofSize: 12); //值的字体大小
        set1.drawFilledEnabled = false; //填充背景
        set1.fillColor = configure.shareConfigure.HMColor1;
        set1.mode = .linear  // 直角， - cublicBezier 圆角  - .stepped 矩形
        
        // let y = arc4random()%500+1; // 随机数
        // 添加数据
        let data = LineChartData.init(dataSets: [set1]);  //[set1,set2]
        lineChartView.data =  data;
        
        //动画
        lineChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0, easingOption: .easeInBack);
        self.addSubview(lineChartView)
    }
    
    // 设置数据
    func setDataCount(_ count: Int, rangeAry: Array<Array<ChartDataEntry>>, style: Dictionary<String,Any>?) {
        
        var i = 0
        var setAry = [IChartDataSet]()
        for ary in rangeAry {
            
            let labelValues = style!["labels"] as! Array<String>
            let colorValues = style!["colors"] as! Array<UIColor>
            
            let set = LineChartDataSet.init(values: ary, label: labelValues[i])
            set.colors = [colorValues[i]] //[configure.shareConfigure.HMColor1];
            set.circleRadius = 5;  //点的大小
            set.drawIconsEnabled = false
            set.drawCircleHoleEnabled = true;  //圆孔启用- 在点上加多一个点
            set.circleHoleRadius = 3; //圆孔启用- 在点上加多一个点的大小
            set.drawCirclesEnabled = true;//绘制转折点
            set.setCircleColor(.gray) //点的颜色
            set.lineWidth = 2.0;
            set.drawValuesEnabled = false; //不显示点上的值
            set.valueFont = UIFont.systemFont(ofSize: 12); //值的字体大小
            set.drawFilledEnabled = false; //填充背景
            set.fillColor = configure.shareConfigure.HMColor1;
            set.mode = .linear  // 直角， - cublicBezier 圆角  - .stepped 矩形
            
            setAry.append(set)
            i += 1
            
        }
        let data = LineChartData.init(dataSets: setAry)
        lineChartView.data = data
    }
    
    // 限制线 value: 最大值？
    func addLimitLine(_ value:Double, _ desc:String) {
        
        let limitLine = ChartLimitLine.init(limit: value, label: desc);
        //线
        limitLine.lineWidth = 3;
//        limitLine.lineColor = UIColor.red;
        limitLine.lineDashLengths = [2.0,2.0];  //断点
        //文字
        limitLine.valueFont = UIFont.systemFont(ofSize: 12.0);
        limitLine.valueTextColor = UIColor.black;
        limitLine.labelPosition = .rightBottom;  //文字位置
        
        lineChartView.leftAxis.addLimitLine(limitLine);
       // lineChartView.leftAxis.removeLimitLine(limitLine);
        
        
    
    }
    
    // 给图添加提示框
    func showMarkerView(_ value: String) {
        let marker = MarkerView.init(frame: CGRect.init(x: 20, y: 20, width: 60, height: 20));
        marker.chartView = lineChartView;
        let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 20));
        label.text = value;
        label.textColor = UIColor.white;
        label.font = UIFont.systemFont(ofSize: 12);
        label.backgroundColor = UIColor.gray;
        label.textAlignment = .center;
        marker.addSubview(label);
        lineChartView.marker = marker;
        
    }


    override func setupViews(view: UIView) {
        drawLineChart()
        // lineChartView.setNeedsDisplay() 更新
    }
    
    override func setJson(json: JSON) {
        
        // 数据
        let data =  json["data"]
        // url id
        let url = json["chartUrl"].stringValue
        // 平均数据
//        var ave =  json["average"]
        // 日平均数
        let averageDaily = json["average"]["daily"][0]
       
        var aveDia = 0.0 //舒张压平均值
        var aveSys = 0.0 //收缩压平均值
        var ave = 0.0  //通用平均值
        if url == "user/data/blood-pressure/day" {
            var accDia = 0.0
            var accSys = 0.0
            for num  in  0..<data.count{
                accDia += Double(data[num]["diastolicPressure"].doubleValue)
                accSys += Double(data[num]["systolicPressure"].doubleValue)
            }
            // 舒张压平均值
            aveDia = accDia / Double(data.count)
            // 收缩压平均值
            aveSys = accSys / Double(data.count)
            
        }else {
            
            var accs = 0.0
            for num in 0..<data.count {
                
                if url == "user/data/weight/day" {
                 accs += Double(data[num]["weight"].doubleValue)
                }else  if url == "user/data/body-temp/day"{
                     accs += Double(data[num]["temp"].doubleValue)
                }else if url == "user/data/heart-rate/day" {
                     accs += Double(data[num]["heartRate"].doubleValue)
                }else if url == "user/data/blood-glucose/day" {
                     accs += Double(data[num]["bloodGlucose"].doubleValue)
                }
            }
            
            
             ave =   accs / Double(data.count) //averageDaily["average"].doubleValue
        }
        
        // 血压
        var systolics = [ChartDataEntry]();
        var diastolics = [ChartDataEntry]();
        // 其他
        var others = [ChartDataEntry]()
        var ary = Array<Array<ChartDataEntry>>()
        var styleDic = Dictionary<String,Any>()
        
        if data.count != 0 {
            for (key, value) in data {
                
                let timeStr = (value["timestamp"].intValue) / 1000
                let strDate =  Date.timeStampToString(timeStamp: String(timeStr))
                //时
                let staHourIndex = strDate.index(strDate.startIndex, offsetBy: 11)
                let endHourIndex = strDate.index(strDate.startIndex, offsetBy: 13)
                let hour = strDate[staHourIndex..<endHourIndex]
                //分
                let staMinIndex = strDate.index(strDate.startIndex, offsetBy: 14)
                let endMinIndex = strDate.index(strDate.startIndex, offsetBy: 16)
                let min = strDate[staMinIndex..<endMinIndex]
                // 计算，分刻度
                let mi =  String(format: "%.2f", Double(min)!/60)
                
                if url == "user/data/blood-pressure/day" {
                    //收缩压
                    let systolic = value["systolicPressure"].doubleValue
                    // 舒张压
                    let diastolic = value["diastolicPressure"].doubleValue
                    //心率
                    // let heart  = value["heartBeat"].doubleValue
                    // 头部的点
                    if key == "0" { //判断的第一个数据
                        if Double(hour) != 1 {
                            
                            let entry = ChartDataEntry.init(x: Double(0), y:aveSys)
                            systolics.append(entry)
                            
                            let entry2 = ChartDataEntry(x: Double(0), y: aveDia)
                            diastolics.append(entry2)
                            
                        }
                    }
                    
                    let  va  =  Double(hour)! + Double(mi)!
                    // 收缩压
                    let entry = ChartDataEntry.init(x: Double(va), y: Double(systolic));
                    systolics.append(entry);
                    
                    // 舒张压
                    let entry2 = ChartDataEntry.init(x: Double(va), y: Double(diastolic));
                    diastolics.append(entry2);
                    
                    // 尾部的点
                    if key ==  "\(data.count - 1)" {
                        if Double(hour) != 24 {
                            let entry = ChartDataEntry.init(x: Double(23), y: aveSys);
                            systolics.append(entry);
                            
                            let entry2 = ChartDataEntry(x: Double(23), y: aveDia)
                            diastolics.append(entry2)
                        }
                    }
                }else  {
                    var double = 0.0
                    if url == "user/data/weight/day" {
                       double = value["weight"].doubleValue
                    }else if url == "user/data/body-temp/day" {
                        double = value["temp"].doubleValue
                    }else if url == "user/data/heart-rate/day" {
                        double = value["heartRate"].doubleValue
                    }else if url == "user/data/blood-glucose/day" {
                        double = value["bloodGlucose"].doubleValue
                    }
                    
                    // 头部的点
                    if key == "0" { //判断的第一个数据
                        if Double(hour) != 1 {
                            let entry = ChartDataEntry.init(x: Double(0), y:ave)
                            others.append(entry)
                        }
                    }
                    
                    let  va  =  Double(hour)! + Double(mi)!
                    // 收缩压
                    let entry = ChartDataEntry.init(x: Double(va), y: Double(double));
                    others.append(entry);
                    
                    
                    // 尾部的点
                    if key ==  "\(data.count - 1)" {
                        if Double(hour) != 24 {
                            let entry = ChartDataEntry.init(x: Double(23), y: ave);
                            others.append(entry);
                        }
                    }
                
                }
            }

        }else {
          // 没有值的时候
            if url == "user/data/blood-pressure/day" {
            
                let entry1_0 = ChartDataEntry.init(x: Double(0), y:Double(-2))
                let entry1_23 = ChartDataEntry.init(x: Double(23), y: Double(-2))
                systolics.append(entry1_0)
                systolics.append(entry1_23)
            
                let entry2_0 = ChartDataEntry(x: Double(0), y: Double(-2))
                let entry2_23 = ChartDataEntry(x: Double(23), y: Double(-2))
                diastolics.append(entry2_0)
                diastolics.append(entry2_23)
            }else {
                let entry1_0 = ChartDataEntry.init(x: Double(0), y:Double(-2))
                let entry1_23 = ChartDataEntry.init(x: Double(23), y: Double(-2))
                others.append(entry1_0)
                others.append(entry1_23)
            }
        }
        
        
        // 刻度范围
        if url == "user/data/blood-pressure/day" {
            ary =  [systolics,diastolics]
            /*
             成人收缩压
             90~139（mmHg）
             成人舒张压
             60~89（mmHg）
             */
            styleDic = ["labels":["收缩压(红色虚线为平均值)","舒张压(黄色虚线为平均值)"], "colors":[configure.shareConfigure.HMColor1, UIColor.red]]
            lineChartView.leftAxis.axisMaximum = 140;  //最大刻度值
            lineChartView.leftAxis.axisMinimum = 20;  //最小刻度值
            lineChartView.leftAxis.granularity = 10 //最小间隔
        }else {
            ary =  [others]
            var label = ""
            if url == "user/data/weight/day" {
                label = "公斤(红色虚线为平均值)"
                lineChartView.leftAxis.axisMaximum = 120;  //最大刻度值
                lineChartView.leftAxis.axisMinimum = 10;  //最小刻度值
                lineChartView.leftAxis.granularity = 10 //最小间隔
            }else if url == "user/data/body-temp/day" {
                label = "度(红色虚线为平均值)"
                lineChartView.leftAxis.axisMaximum = 40;  //最大刻度值
                lineChartView.leftAxis.axisMinimum = 4;  //最小刻度值
                lineChartView.leftAxis.granularity = 4 //最小间隔
            }else if url == "user/data/heart-rate/day" {
                label = "次数(红色虚线为平均值)"
                lineChartView.leftAxis.axisMaximum = 140;  //最大刻度值
                lineChartView.leftAxis.axisMinimum = 20;  //最小刻度值
                lineChartView.leftAxis.granularity = 10 //最小间隔
            }else if url == "user/data/blood-glucose/day" {
                label = "毫摩尔/升(红色虚线为平均值)"
                lineChartView.leftAxis.axisMaximum = 20;  //最大刻度值
                lineChartView.leftAxis.axisMinimum = 1;  //最小刻度值
                lineChartView.leftAxis.granularity = 0 //最小间隔
            }
            
            styleDic = ["labels":[label], "colors":[configure.shareConfigure.HMColor1]]
        }
        
        
    
        
        //设置数据
        self.setDataCount(systolics.count, rangeAry: ary, style: styleDic)
        
        
//            self.addLimitLine(averageDaily["diaAverage"].doubleValue, "舒张压平均线");
    }
}

extension ChartViewCell: ChartViewDelegate {
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        print("entry=======>>", entry, highlight);
        showMarkerView("\(entry.y)")
    }
    func chartValueNothingSelected(_ chartView: ChartViewBase) {
        NSLog("chartValueNothingSelected");
    }
    
    func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
        
    }
    
    func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
        
    }
    
}


// 这个什么鬼
class VDChartAxisValueFormatter: NSObject,IAxisValueFormatter {
    var values:NSArray?;
    override init() {
        super.init();
    }
    init(_ values: NSArray) {
        super.init();
        self.values = values;
    }
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        if values == nil {
            return "\(value)";
        }
        return values?.object(at: Int(value)) as! String;
    }
}

